package org.telegram.bot.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.delay.IDelayEvent;
import com.ruoyi.common.core.delay.ItemDelayed;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.telegram.bot.domain.BotMessage;
import org.telegram.bot.handle.IBotSendMessage;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.DeleteMessage;

import java.util.Iterator;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Author: wyx
 * @Date: 2023/5/29 20:48
 */
@Slf4j
@Service
public class DelayDeleteBotMessageImpl implements IDelayEvent<BotMessage> , IBotSendMessage {

    private final static DelayQueue<ItemDelayed<BotMessage>> DELAY_QUEUE = new DelayQueue<>();

    /**
     * 初始化时加载
     * 系统启动:扫描数据库
     */
    @PostConstruct
    public void init() {
        Thread thread = new Thread(() -> {
            ItemDelayed<BotMessage> validateItemDelayed;
            while (true) {
                try {
                    validateItemDelayed = DELAY_QUEUE.take();
                    //删除消息
                    send(validateItemDelayed.getData().getBotId(),
                            DeleteMessage.builder()
                                    .chatId(validateItemDelayed.getData().getChatId())
                                    .messageId(validateItemDelayed.getData().getMessageId()).build());
                    
                } catch (Exception e) {
                    log.error("删除消息_执行_延迟队列_异常:{},{}",JSONObject.toJSONString(e),e.fillInStackTrace());
                }
            }
        });
        thread.start();
    }
    /**
     * 添加延迟对象到延时队列
     *
     * @param itemDelayed 延迟对象
     * @return boolean
     */
    @Override
    public boolean addToItemDelayedQueue(ItemDelayed<BotMessage> itemDelayed) {
        return DELAY_QUEUE.add(itemDelayed);
    }

    /**
     * 根据对象添加到指定延时队列
     *
     * @param data 数据对象
     * @return boolean
     */
    @Override
    public boolean addToDelayQueue(BotMessage data) {
        ItemDelayed<BotMessage> orderDelayed = new ItemDelayed<>(data.getId(), data.getCreateTime().getTime(),data,data.getTimeout(), TimeUnit.SECONDS);
        return DELAY_QUEUE.add(orderDelayed);
    }

    /**
     * 移除指定的延迟对象从延时队列中
     *
     * @param data
     */
    @Override
    public void removeToDelayQueue(BotMessage data) {
        if (data == null) {
            return;
        }
        for (Iterator<ItemDelayed<BotMessage>> iterator = DELAY_QUEUE.iterator(); iterator.hasNext(); ) {
            ItemDelayed<BotMessage> queue = iterator.next();
            if (queue.getDataId().equals(data.getId())) {
                DELAY_QUEUE.remove(queue);
            }
        }
    }

    @Override
    public BotMessage getData(Long dataId) {
        if (dataId != null) {
            for (Iterator<ItemDelayed<BotMessage>> iterator = DELAY_QUEUE.iterator(); iterator.hasNext(); ) {
                ItemDelayed<BotMessage> queue = iterator.next();
                if (queue.getDataId().equals(dataId)) {
                    return queue.getData();
                }
            }
        }
        return null;
    }
}
